/**
 * Created by lizhihang
 */

'use strict';
var express = require('express');
var router = express.Router();
var request = require('request');
var async = require('async');
var logger = require('../logger');
var superagent = require('superagent');
var jwt = require('jsonwebtoken');
var mongo = require('mongoskin');
var http = require("http");
var fs = require("fs");
var yzmService = require("./yzmService");
var redis = require("redis");
var client = redis.createClient(6379,"127.0.0.1");
var User = require('../models/User')


var db = mongo.db("mongodb://localhost:27017/weGDUT");
db.bind('weGDUT');
/**
 * Test Login
 *
 */
function course(req, res, next) {
    var token = req.body.token
    
    if (token) {
        //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
        try {
             let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            //  console.log(decoded)
             let username  = decoded.username
             yzmService.getCookieFromRedis(username).then(function(value){
                //  console.log('redis value:'+value)
                 if(value != ''){
                    let cookie = value
                    getCourse(cookie).then(function (value) {
												var rows = JSON.parse(value)
												 var all = {total:rows[0].length, rows:rows[0]};
                        
                        res.send({ code: 200, message: 'ok', 'data':all })
                    })
                 }else{
                     res.send({code:505, message:'cookie过期'})
                 }
             })
            // let openid = decoded.openid;
            // //查找数据库中是否已经绑定
            // var result = new Promise((resolve, reject) => {
            //     db.weGDUT.find({ openid: openid }).toArray(function (err, items) {
            //         resolve(items)
            //     })
            // })
            // var users;
            // result.then(function (value) {
            //     users = value[0]
            //     if (!users.username) {
            //         res.send({ code: 505, message: 'Not Bind' })
            //     } else {
            //         //找到该用户
            //         let username = users.username
            //         let password = users.password
                //     var cookie = yzmService.getCookieFromRedis(username)
                //     cookie.then(function(cookie){
                //         // 如果返回的cookie为空
                //         if(!cookie){
                //             getCookie(username, password).then(function (cookie) {
                //             getCourse(cookie).then(function (value) {
                //                 res.send({ code: 200, message: 'ok', 'data': JSON.parse(value) })
                //                 })
                //             })
                //         }else{
                //             // 如果cookie存在，直接带cookie请求
                //             getCourse(cookie).then(function (value) {
                //                 res.send({ code: 200, message: 'ok', 'data': JSON.parse(value) })
                //                 })
                //             }
                //         })
                //     }
                // })    
        } catch (err) {
            res.send({ code: 401, message: 'token invid' })
        }
    } else {
        res.send({ code: 402, message: 'token is required' })
    }
}

/**
 * course2017
 *
 */
async function courseNext(req, res, next) {
    var token = req.body.token
    if (token) {
        //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
        try {
            let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            //  console.log(decoded)
             let username  = decoded.username
             let check = await checkIfExistCourse(username);
             if (!check) {
                yzmService.getCookieFromRedis(username).then(function(value){
                    if(value != ''){
                        let cookie = value
                        getCourse2017(cookie).then(function (value) {
                            var rows = JSON.parse(value)
                            var all = {total:rows[0].length, rows:rows[0]};
                            User.update({account:username}, {course:all}, (err, reply) => {
                                if (err) {
                                    console.log(err)
                                } else {
                                    console.log('update course successfully')
                                }
                            });
                            res.send({ code: 200, message: 'ok', 'data':all })
                        })
                    }else{
                        res.send({code:505, message:'cookie过期'})
                    }
                })
            } else {
                res.send({ code: 200, message: 'ok', 'data':check })
            }
            
            // let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            // console.log(decoded)
            // let openid = decoded.openid;
            // //查找数据库中是否已经绑定

            // var result = new Promise((resolve, reject) => {
            //     db.weGDUT.find({ openid: openid }).toArray(function (err, items) {
            //         resolve(items)
            //     })
            // })
            // var users;
            // result.then(function (value) {
            //     users = value[0]
            //     if (!users.username) {
            //         res.send({ code: 505, message: 'Not Bind' })
            //     } else {
            //         //找到该用户
            //         let username = users.username
            //         let password = users.password
            //         var cookie = yzmService.getCookiegetCookieFromRedis(username)
            //         cookie.then(function(cookie){
            //             // 如果返回的cookie为空
            //             if(!cookie){
            //                 getCookie(username, password).then(function (cookie) {
            //                 getCourse2017(cookie).then(function (value) {
            //                     res.send({ code: 200, message: 'ok', 'data': JSON.parse(value) })
            //                     })
            //                 })
            //             }else{
            //                 getCourse2017(cookie).then(function (value) {
            //                     res.send({ code: 200, message: 'ok', 'data': JSON.parse(value) })
            //                     })
            //             }
            //         })
            //     }
            // })
        } catch (err) {
            res.send({ code: 401, message: 'token invid' })
        }
    } else {
        res.send({ code: 402, message: 'token is required' })
    }
}         

function checkIfExistCourse(account) {
    return new Promise((resolve, reject) => {
        User.findOne({account:account}, (err, res) => {
            if ('course' in res) {
                resolve(0)
            } else {
                resolve(res.course)
            }
        })
    })
}

/**
 * 功能：获取考试的时间安排
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function exam(req, res, next) {
    var token = req.body.token
    console.log(token)
    if (token) {
        //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
        try {
            let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            // console.log(decoded)
            let openid = decoded.openid;
            //查找数据库中是否已经绑定

            var result = new Promise((resolve, reject) => {
                db.weGDUT.find({ openid: openid }).toArray(function (err, items) {
                    resolve(items)
                })
            })
            var users;
            result.then(function (value) {
                users = value[0]
                console.log(users)
                if (!users.username) {
                    res.send({ code: 505, message: 'Not Bind' })
                } else {
                    //找到该用户
                    let username = users.username
                    let password = users.password
                    getCookie(username, password).then(function (cookie) {
                        getExam(cookie).then(function (value) {
                            res.send({ code: 200, message: 'ok', 'data': JSON.parse(value) })
                        })
                    })
                }
            })

        } catch (err) {
            res.send({ code: 401, message: 'token invid' })
        }
    } else {
        res.send({ code: 402, message: 'token is required' })
    }
}

/**
 * 功能：获取考试的时间安排
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function score(req, res, next) {
    var token = req.body.token
    // console.log(token)
    //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
    
     if (token) {
        try {
            let decoded = jwt.verify(token, 'thefirstminappofvtmer');
                // console.log(decoded)
                let username  = decoded.username
                yzmService.getCookieFromRedis(username).then(function(value){
                    if(value !=''){
                        let cookie = value
                        getScore(cookie).then(function (value) {
                            res.send({ code: 200, message: 'ok', 'data': value })
                        })
                    }else{
                        res.send({code:505, message:'cookie过期'})
                    }
                })
       
        //     let decoded = jwt.verify(token, 'thefirstminappofvtmer');
        //     //console.log(decoded)
        //     let openid = decoded.openid;
        //     //查找数据库中是否已经绑定
        //     var result = new Promise((resolve, reject) => {
        //         db.weGDUT.find({ openid: openid }).toArray(function (err, items) {
        //             resolve(items)
        //         })
        //     })
        //     var users;
        //     result.then(function (value) {
        //         users = value[0]
        //         console.log(users)
        //         if (!users.username) {
        //             res.send({ code: 505, message: 'Not Bind' })
        //         } else {
        //             //找到该用户
        //             let username = users.username
        //             let password = users.password
        //             var cookie = yzmService.getCookieFromRedis(username)
        //             cookie.then(function(cookie){
        //                 // 如果返回的cookie为空
        //                 if(!cookie){
        //                     getCookie(username, password).then(function (cookie) {
        //                         getScore(cookie).then(function (value) {
        //                             res.send({ code: 200, message: 'ok', 'data': value })
        //                         })
        //                     })
        //                 }else{
        //                     getScore(cookie).then(function (value) {
        //                         res.send({ code: 200, message: 'ok', 'data': value })
        //                     })
        //                 }
        //             })
        //         }
        //     })
        } catch (err) {
            res.send({ code: 401, message: 'token invid' })
        }
    } else {
        res.send({ code: 402, message: 'token is required' })
    }
}



   
/**
 * 功能：获取登陆成功后的token
 * @param {char} username 
 * @param {char} password 
 */

// function getCookie(username, password) {
    
//     //通过 promise 处理异步请求
//     return new Promise((resolve, reject) => {
//         const baseUrl = 'http://jxfw.gdut.edu.cn/login!doLogin.action'
//         let formData = {
//             account: '3114006472',//,username,//
//             pwd: '472040743lzh',//password,//,
//             verifycode: '',
//         }
//         let result = {};    // 结果数据
//         superagent.post(baseUrl)  
//             .type("form")
//             .send(formData)
//             .end(function (err, res) {
//                 if (err) throw err                
//                 let cookie = res.header['set-cookie']          //从response中得到cookie
//                 resolve(cookie)
//             })
//     })
// }




/**
 * 功能：拿到课表并且返回给上面的 score 函数
 * @param  {char|JSSEEION：********} cookie 
 */
function getScore(cookie) {
    return new Promise((resolve, reject) => {
        
        const baseUrl = 'http://jxfw.gdut.edu.cn/xskccjxx!getDataList.action'
        let formData = {
            xnxqdm: '',
            jhlxdm: '',
            page: 1,
            rows: 150,
            sort: 'xnxqdm',
            order: 'asc'
        }
        console.log('cookie at getScore'+cookie)
        superagent.post(baseUrl)
            .set("Cookie", cookie) 
            .set('Referer', "http://jxfw.gdut.edu.cn/xskccjxx!xskccjList.action?firstquery=1")      //设置上面已经登陆的 token
            .type("form")
            .send(formData)
            .end(function (err, res) {
                if (err) {
                    throw err
                }
                // console.log(res.text)
                var score = JSON.parse(res.text).rows
                var handle = {
                    1:'大一上',
                    2:'大一下',
                    3:'大二上',
                    4:'大二下',
                    5:'大三上',
                    6:'大三下',
                    7:'大四上',
                    8:'大四下'
                }
                // console.log(score);
                var tempxq = score[0].xnxqmc
                var xq =1;
                var result = {}
                result[handle[xq]] = []
               
                for(var i in score){
                    
                    if(score[i].xnxqmc === tempxq){
                        //console.log(score[i].xnxqdm)
                        result[handle[xq]].push(score[i]) 
                    }else{
                        tempxq = score[i].xnxqmc
                        xq++
                        result[handle[xq]] = []
                        result[handle[xq]].push(score[i]) 
                    }
                }
                // console.log(result)
                result['全部'] = score
                resolve(result);
            })
    });
};


/**
 * 功能：拿到考试安排并且返回给上面的 exam 函数
 * @param {char|JSSEEION：********} cookie 
 */
function getExam(cookie) {
    return new Promise((resolve, reject) => {
        const baseUrl = 'http://jxfw.gdut.edu.cn/xsksap!getDataList.action'
        superagent.get(baseUrl)
            .set("Cookie", cookie)
            .end(function (err, res) {
                if (err) {
                    throw err
                };
                //console.log(res.text)
                resolve(res.text)
            })
    });
};

/**
 * 功能：拿到课表并且返回给上面的 course 函数
 * @param  {char|JSSEEION：********} cookie 
 */
function getCourse(cookie) {
    return new Promise((resolve, reject) => {
        const baseUrl = 'http://jxfw.gdut.edu.cn/xsbjkbcx!getKbRq.action'
        let formData = {
            xnxqdm: '201701',
            zc: '',
            page: 1,
            rows: '200',
            sort: 'zc,xq',
            order: 'asc',
        }
        superagent.post(baseUrl)
            .set("Cookie", cookie)       //设置上面已经登陆的 token
            .type("form")
            .send(formData)
            .end(function (err, res) {
                if (err) {
                    throw err
                };
                // console.log(res.text)
                resolve(res.text);
            })
    });
};

/**
 * 功能：拿到201701课表并且返回给上面的 course 函数
 * @param  {char|JSSEEION：********} cookie 
 */
function getCourse2017(cookie) {
    return new Promise((resolve, reject) => {
        //const baseUrl = 'http://jxfw.gdut.edu.cn/xsbjkbcx!getKbRq.action'
        
        const baseUrl = 'http://jxfw.gdut.edu.cn/xsgrkbcx!getKbRq.action'
        let formData = {
            xnxqdm: '201702',
            zc: '',
            page: 1,
            rows: '200',
            sort: 'zc,xq',
            order: 'asc',
        }
        superagent.post(baseUrl)
            .set("Cookie", cookie)       //设置上面已经登陆的 token
            .type("form")
            .send(formData)
            .end(function (err, res) {
                if (err) {
                    throw err
                };
                //console.log(res.text)
                resolve(res.text);
            })
    });
};
/**
 * 登录教务系统，获取cookie
 * @param {string} username 
 * @param {string} password 
 */
function getCookie(username,password) {
	return new Promise((resolve,reject) => {
		var Imgurl = yzmService.getYZM();
    	Imgurl.then(function(value){
		var Imgurl = value.saveUrl;
		let cookie = value.cookie;
		// console.log(cookie)
        var yzmNum = yzmServce.yzmRecognize(Imgurl);
        yzmNum.then(function(value){
			var yzmNum = value;
            const baseUrl = 'http://jxfw.gdut.edu.cn/login!doLogin.action'
			let formData = {
				account: username,//'3114006472'
				pwd: password,//'472040743lzh'
				verifycode: yzmNum,
			}
			// console.log(formData)
			superagent.post(baseUrl)
				.set("Cookie", cookie)
				.type("form")
				.send(formData)
				.end(function (err, res) {
					if (err) {
						reject(err);
					};
					let result = JSON.parse(res.text)
					//console.log(result);
					//console.log(res.header)
					if (result.status === 'y') {
						// console.log(result)
				    client.HMSET('cookie:' + username,{'username':username,'cookie':cookie})
						resolve(cookie)
					} else {
						console.log('fail to login:' + username)
					}	
				})
    		})
    	})     
	})
}


module.exports = { course, courseNext, exam, score};
